#pragma once

#include <iostream>
#include <string>
#include "easylogging++.h"
#include <sys/syscall.h>
#include <unistd.h>
#include "common.h"

class LogHandler
{
public:
    LogHandler(const char *log_path)
    {
        //初始化日志系统
        el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%sys_thread", getIp));
        el::Configurations conf{log_path};
        conf.setGlobally(el::ConfigurationType::MaxLogFileSize, "10485760000");
        el::Loggers::reconfigureAllLoggers(conf);
        el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
        el::Helpers::installPreRollOutCallback(rolloutHandler);
    }

    static const char *getIp(const el::LogMessage *)
    {
        return std::to_string(syscall(SYS_gettid)).c_str();
    }

    static void rolloutHandler(const char *filename, std::size_t size)
    {
        // SHOULD NOT LOG ANYTHING HERE BECAUSE LOG FILE IS CLOSED!
        std::cout << "************** Rolling out [" << filename << "] because it reached [" << size << " bytes]" << std::endl;
        std::string creation_time = FileHandler::get_creation_time(filename);
        // BACK IT UP
        std::stringstream ss;
        ss << "mv " << filename << " logs/server-" << creation_time << ".log";
        system(ss.str().c_str());
    }
};